/**
 * tag controller
 */

const mongoose = require('mongoose')
const Tag = mongoose.model('Tag')
const Log = mongoose.model('Log')
const LogMethods = require('./log')

const addTag = async(ctx, next) => {
	const tag = ctx.request.body
	if (!tag.name) {
		return ctx.body = {
			success: false,
			message: '标签名称不能为空'
		}
	}
	try {
		const t = await Tag.findOne({
			name: tag.name
		})
		if (t) {
			return ctx.body = {
				success: false,
				message: '标签名称重复'
			}
		}
		const newTag = await new Tag(tag).save()
		ctx.body = {
			success: true,
			data: {
				id: newTag._id
			}
		}
		LogMethods.createLog(ctx.session.userid, 'NEW_TAG', `新建了标签${newTag.name}`)
	} catch (e) {
		ctx.throw(400, '添加标签失败')
	}
}

const deleteTag = async(ctx, next) => {
	const id = ctx.params.id
	try {
		await Tag.findByIdAndRemove(id)
		ctx.body = {
			success: true,
			message: '删除成功'
		}
		LogMethods.createLog(ctx.session.userid, 'DELETE_TAG', `删除了标签${id}`)
	} catch (e) {
		ctx.throw(400, '删除失败')
	}
}

const updateTag = async(ctx, next) => {
	const id = ctx.params.id
	if (ctx.request.body._id) {
		delete ctx.request.body._id
	}
	try {
		const result = await Tag.findByIdAndUpdate(id, {
			$set: {
				name: ctx.request.body.name
			}
		})
		ctx.body = {
			success: true,
			data: {
				id: result._id
			}
		}
		LogMethods.createLog(ctx.session.userid, 'UPDATE_TAG', `更新了标签${id}, 名称为${result.name}`)
	} catch (e) {
		ctx.throw(400, '更新标签失败')
	}
}

const getFrontTagsList = async(ctx, next) => {
	try {
		const list = await Tag.find({
			is_show: true
		}, '_id name')

		ctx.body = {
			success: true,
			data: {
				list: list
			}
		}
	} catch (e) {
		ctx.throw(400, '获取列表失败')
	}
}

/**
 * server 获取标签列表
 */
const getTagList = async(ctx, next) => {
	try {
		const list = await Tag.find({}, '_id name is_show')
		ctx.body = {
			success: true,
			data: {
				list
			}
		}
	} catch (e) {
		ctx.throw(400, '获取标签列表失败')
	}
}

module.exports = {
	addTag,
	deleteTag,
	updateTag,
	getFrontTagsList,
	getTagList
}